// server.js
const app = require('express')()
const { createBundleRenderer } = require('vue-server-renderer')
const fs = require('fs')
const path = require('path')
const chalk = require("chalk")
const address = require("address")
const resolve = file => path.resolve(__dirname, file)

const isProd = process.env.NODE_ENE === "production"

const createRenderer = (bundle, options) => {
    return createBundleRenderer(bundle, Object.assign(options, {
        basedir: resolve('./dist'),
        runInNewContext: false,
    }))
}

let renderer, readyPromise
const templatePath = resolve('../src/index.template.html')
if (isProd) {
    const bundle = require('./dist/vue-ssr-server-bundle.json')
    const clientManifest = require('./dist/vue-ssr-client-manifest.json')
    const template = fs.readFileSync(templatePath, 'utf-8')

    renderer = createRenderer(bundle, {
        // 推荐
        template, // （可选）页面模板
        clientManifest // （可选）客户端构建 manifest
    })
} else {
    // 开发模式
    readyPromise = require('../config/setup-dev-server')(app, templatePath, (bundle, options) => {
        renderer = createRenderer(bundle, options)
    })
}

const render = (req, res) => {
    const context = {
        title: 'hello ssr with webpack',
        meta: `
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
    `,
        url: req.url
    }
    renderer.renderToString(context, (err, html) => {
        if (err) {
            if (err.code === 404) {
                res.status(404).end('Page not found')
            } else {
                res.status(500).end('Internal Server Error')
            }
        } else {
            res.end(html)
        }
    })
}

// 在服务器处理函数中……
app.get('*', isProd ? render : (req, res) => {
    readyPromise.then(() => render(req, res))
})

const port = '8081';
app.listen(port, () => {
    const appRunningStr = chalk.green("App running at")
    const LOCAL_IP = address.ip()
    const localStr = chalk.green("Local:  ") + chalk.cyan(`http://localhost:${port}`)
    const netWorkStr = chalk.green("Network:") + chalk.cyan(`http://${LOCAL_IP}:${port}`)
    console.log(appRunningStr)
    console.log(localStr)
    console.log(netWorkStr)
})
